package com.crazy.proxy;

import cn.hutool.aop.aspects.Aspect;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;

/**
 * @author panyonghui
 * @describe 基于cglib动态代理
 * @date 2023/1/6 9:48
 */
public class CglibProxy {
    /**
     * @describe
     * @param target 被代理类的对象
     * @param aspectClass 需要执行的切面类
     * @return T
     * @modify
     */
    public static <T> T getProxyInstance(T target, Class aspectClass) {
        Aspect aspect = null;
        try {
            aspect = (Aspect) aspectClass.newInstance();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        Aspect finalAspect = aspect;
        MethodInterceptor methodInterceptor = (o, method, objects, methodProxy) -> {
            // 原方法执行前的额外任务
            finalAspect.before(target, method, objects);
            // target：被代理类的对象
//            Object result = methodProxy.invoke(target, objects);
//            Object result = methodProxy.invokeSuper(o, objects);
            Object result = method.invoke(target, objects);
            // 执行完原方法后可执行额外的任务
            finalAspect.after(target, method, objects, result);
            return result;
        };
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(target.getClass());
        enhancer.setCallback(methodInterceptor);
        return (T)enhancer.create();
    }
}
